﻿@{
    PassportConfiguration passportConfig = this.Model.Data;
    var verifyConfig = ConfigurationFactory.GetConfig<VerifyConfiguration>();
    var fileHost = ConfigurationFactory.CommonSettings["file"];
    var randcodeAction = Url.Content(verifyConfig.RandCodeUrl);
    var matchcodeAction = Url.Content(verifyConfig.MatchCodeUrl);
    VerifySetting verifySetting = verifyConfig.VerifySettings[this.Context.Request.Path.ToString().ToLower()];
    var enableValidCode = verifySetting.Enabled;

    string? authTicket = this.Context.Request.Query[OpenAuthKey.AUTH_TICKET];
    authTicket = string.IsNullOrWhiteSpace(authTicket) ? new Ticket(SequenceGUID.NewGUID()) : authTicket;
    var signinAction = this.Url.Content("~/passport/bind");

    var slideBgAction = this.Url.Content($"{fileHost}/rand/load/slides");
}
@section head {
    <title>MiniFox Studio - 绑定账号</title>
    <link href="~/static/css/auth.css" rel="stylesheet" />
    <script type="text/javascript">

        $(function () {
            var authTicket = "@Html.Raw(authTicket)";
            var parameters = {
                "@(OpenAuthKey.AUTH_TICKET)": authTicket,
                "@(GlobalKey.VALID_TICKET)": authTicket
            };
            var service = MiniFox.createService({
                "defaults": {
                    "host": {
                        "OAUTH2": "",
                        "BASE": "",
                        "validation": ""
                    },
                    "autoMsg": false,
                    "timeOut": 120000,
                    "enableCookies": false,
                    "method": "post"
                },
                "adapters": [
                    {
                        "name": "oauth2",
                        "host": "OAUTH2",
                        "virtualPath": "",
                        "api": [
                            {
                                "name": "signin",
                                "url": "@(signinAction)",
                                "enableCookies": false,
                                "showProcessing": true,
                                "headers": parameters,
                                "params": parameters,
                                "autoMsg": true,
                                "method": "post"
                            }
                        ]
                    },
                    {
                        "name": "common",
                        "host": "BASE",
                        "virtualPath": "",
                        "api": [
                            {
                                "name": "file",
                                "url": "@slideBgAction",
                                "method": "get",
                                "noAjax": true,
                                "params": {
                                    "fileId": "default"
                                }
                            }
                        ]
                    },
                    {
                        "name": "validation",
                        "host": "",
                        "virtualPath": "",
                        "api": [
                            {
                                "name": "randcode",
                                "url": "@randcodeAction",
                                "method": "get",
                                "noAjax": true
                            },
                            {
                                "name": "matchcode",
                                "url": "@matchcodeAction",
                                "autoMsg": true,
                                "method": "get"
                            }
                        ]
                    }
                ]
            });

            var taskPool = new MiniFox.TaskPool();
            var slidesTask = new MiniFox.Task("slide", {
                interval: 30000,
                onAction: function () {
                    service.common.file.params["_"] = Math.random();
                    var bgimgUrl = service.common.file.toString();
                    $('#img_bg').prop('src', bgimgUrl);
                    MiniFox.debounce(function () {
                        $(document.body).css('background-image', 'url(' + bgimgUrl + ')');
                    }, 30000)();
                }
            });
            taskPool.addTask(slidesTask, true);

            var enabledValidCode = @(enableValidCode.ToString().ToLower());
            var validRequired = @((verifySetting.RetryTimes <= 0).ToString().ToLower());
            var validAsync = @(verifySetting.Async.ToString().ToLower());
            var retryTimes = 0;
            var reset = function () {

                $("#img_ValidCode").click();
                $("#btn_SignIn").button('reset');
                $("#signin").find("input").removeAttr("disabled");
            };
            $("#img_ValidCode").click(function () {
                var uri = new MiniFox.Uri($(this).attr("base-url") || service.validation.randcode);
                uri.addParams({
                    ticket: authTicket,
                    _: Math.random()
                });
                var src = uri.toString();
                $(this).attr("src", src);

            });
            var setValidCode = function () {

                //显示验证码
                $("#validCodeContainer").show();
                $("#img_ValidCode").click();

            };
            if (validRequired) {
                setValidCode();
            }
            var signin = function () {

                var params = {};
                var headers = {};
                if (enabledValidCode && !validAsync) {
                    headers["@(GlobalKey.VALID_CODE)"] = $("#ValidCode").val();
                    params["@(GlobalKey.VALID_CODE)"] = $("#ValidCode").val();
                }
                var postData = {
                    signName: $("#signName").val(),
                    password: $("#password").val()
                };

                service.oauth2.signin({
                    params: params,
                    data: postData,
                    headers: headers,
                    beforeSend: function (xhr) {
                        $("#btn_SignIn").button('loading');
                        $("#signin").find("input").attr("disabled", "disabled");
                        return true;
                    },
                }).then(function (response) {

                    if (response.success) {
                        window.location.href = response.redirectUri;
                    }
                    else {
                        reset();
                        if (++retryTimes >= @(verifySetting.RetryTimes)) {
                            validRequired = true;
                            setValidCode();
                        }
                    }
                }).catch(function () {
                    reset();
                });

            };

            $("#btn_SignIn").click(function () {
                if (enabledValidCode && validAsync && validRequired) {

                    var params = {
                        ticket: authTicket,
                        code: $("#ValidCode").val()
                    };
                    service.validation.matchcode({ params: params }).then(function (response) {
                        if (response.success) {
                            signin();
                        }
                        else {
                            $("#img_ValidCode").click();
                        }
                    });
                }
                else {
                    signin();
                }
            });
        });


    </script>

}

<div class="container">
    <div class="form-signin">



        <form class="form-horizontal" id="signin" name="signin" action="@signinAction" commitbutton="btn_SignIn" method="post">
            <h2 class="form-signin-heading">用户绑定</h2>
            <div class="form-group">
                <div class="input-group">
                    <div class="input-group-addon" id="ico_SignName"></div>
                    @Html.TextBox("signName", string.Empty, new { Class = "form-control input-sm", placeholder = "用户名/邮箱/手机号" })
                </div>
            </div>
            <div class="form-group">
                <div class="input-group">
                    <div class="input-group-addon" id="ico_Password"></div>
                    @Html.Password("password", string.Empty, new { Class = "form-control input-sm", placeholder = "密码" })
                </div>
            </div>
        @if (enableValidCode)
        {
            <div class="form-group" id="validCodeContainer" style="display: none;">
                @Html.Label("lab_validCode", "验证码", new { Class = "sr-only" })
                <div class="input-group">
                    @Html.TextBox("validCode", string.Empty, new { Class = "form-control input-sm", autocomplete = "off", placeholder = "验证码" })
                    <div class="input-group-addon">
                        @Html.ValidCode("validCode", randcodeAction, new { alt = "点击图片换一张" })
                    </div>
                </div>

            </div>

        }
            <div class="form-group">
                <button id="btn_SignIn" onclick="return false" data-loading-text="正在登录..." class="btn btn-lg btn-primary btn-block">绑       定</button>
            </div>
        </form>

        <p>
            本系统不适用于IE8.0(含)以下版本的IE浏览器，请使用IE9以上版本、Edge、火狐或Google浏览器
        </p>
        <p>
            推荐使用Edge、火狐(Firefox)或Google浏览器
        </p>
        <img id="img_bg" style="display:none" />
    </div>
</div>